<?php
/**
 * @author: zhouzhongyuan <435690026@qq.com>
 * @copyright 万虎网络
 * @link http://www.wanhunet.com
 */

namespace common\Utils;

use Yii;
use yii\base\Model;
use yii\helpers\Url;

class Info
{
    const ERROR = "error";
    const DANGER = "danger";
    const SUCCESS = "success";
    const INFO = "info";
    const WARNING = "warning";
    private $_infos = [];


    /**
     * @param array|Model $infos
     * @param array $url
     * @param int $statusCode
     * @return static
     */
    public static function redirectWithInfo($infos = [], $url = [], $statusCode = 302)
    {
        if (Yii::$app->request->isPost) {
            Yii::$app->getSession()->setFlash("INFO_POST", Yii::$app->request->post());
        }

        if ($infos instanceof Model) {
            $infos = $infos->getFirstErrors();
            foreach ($infos as $type => $info)
                \Yii::$app->getSession()->setFlash(self::ERROR, $info);
        } elseif (is_array($infos)) {
            foreach ($infos as $type => $info)
                \Yii::$app->getSession()->setFlash($type, $info);
        }

        return
            count($url) == 0 ?
                \Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl()) :
                Yii::$app->getResponse()->redirect(Url::to($url), $statusCode);
    }

    public static function formValue($attrName, $defaultValue = '')
    {
        $post = Yii::$app->getSession()->getFlash("INFO_POST");
        return isset($post[$attrName]) ? $post[$attrName] : $defaultValue;
    }

    public static function formCheck($attrName, $value, $defaultValue = '')
    {
        $post = Yii::$app->getSession()->getFlash("INFO_POST");
        return isset($post[$attrName][$value]) ? "checked" : $defaultValue;
    }

    public function with($type, $info)
    {
        $this->_infos[$type] = $info;
    }

    public function withModel(Model $model)
    {
        $this->_infos = $model;
    }

    public function redirect($url = [], $statusCode = 302)
    {
        return self::redirectWithInfo($this->_infos, $url, $statusCode);
    }

}